package com.caiheng.api.controller.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.examine.ExamineApproveRegRecord;
import com.caiheng.api.entity.titlemenu.TitleMenu;
import com.caiheng.api.service.examine.ExamineApproveRegRecordService;
import com.caiheng.api.service.titlemenu.TitleMenuService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.mer.MerUser;
import com.caiheng.api.entity.platform.*;
import com.caiheng.api.entity.product.OrderItemArr;
import com.caiheng.api.entity.product.ProductOrder;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.*;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.mer.MerService;
import com.caiheng.api.service.mer.MerUserService;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.product.ProductOrderService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.*;
import com.vdurmont.emoji.EmojiParser;

import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/user")//url:模块/资源/{}/细分
public class UserController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserMpService userMpService;
    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private AdBannerService adBannerService;
    @Resource
    private FeedBackService feedBackService;
    @Resource
    private SmsTemplateService smsTemplateService;
    @Resource
    private PropertyFeeOrderService propertyFeeOrderService;
    @Resource
    private MerUserService merUserService;
    @Resource
    private MerService merService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private RepairRecordService repairRecordService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private MapAreaService mapAreaService;
    @Resource
    private WxMpUserRelationService wxMpUserRelationService;
    @Resource
    private CityService cityService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private TitleMenuService titleMenuService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private EstateRoomBangUserService estateRoomBangUserService;
    @Resource
    private ExamineApproveRegRecordService approveRegRecordService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${web.imgUrl}")
    private String imgUrl;//图片地址
    @Value("${web.imgPrefixOss}")
    private String imgUrlOss;//图片地址
    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址
    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.appid}")
    private String appid;//图片地址
    @Value("${web.secret}")
    private String secret;//图片地址

    @Value("${web.appidWork}")
    private String appidWork;//图片地址
    @Value("${web.secretWork}")
    private String secretWork;//图片地址


    /**
     * 微信登录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject Test(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
//            if(StrUtil.isEmpty(requestParam)){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
//            }
            logBefore(logger, "user/test 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            boolean bl = mapAreaService.isInArea(new BigDecimal(119.470713),new BigDecimal(35.447712),0);
//            userRegCashRecordService.addTransaction();
//            User user = userService.findById(1);
//            long count = userRegCashRecordService.getUserShareCount(user.getId());

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"登录成功"),true,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 联系方式的添加
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/mp/web")
    public JSONObject addMpWebUser(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String ,Object> map = new HashMap<String, Object>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/add/mp/web 接收的参数： "+requestParam);
            System.out.println("wxLogin 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String real_name = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : null;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : null;


            if(StrUtil.isEmpty(real_name)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "姓名不能为空"), true, true);
            }


            if(StrUtil.isEmpty(phone_num)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "联系方式不能为空"), true, true);
            }


            boolean blValidate = Tools.isSqlValid(real_name);
            if(!blValidate){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "存在违禁词，修改后再输入"), true, true);
            }


            blValidate = Tools.isSqlValid(phone_num);
            if(!blValidate){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "存在违禁词，修改后再输入"), true, true);
            }

            WxMpUserRelation userRelation = new WxMpUserRelation();
            userRelation.setPhoneNum(phone_num);
            userRelation.setRealName(real_name);
            userRelation.setState(0);
            userRelation.setCreateTime(new Date());

            boolean bl = wxMpUserRelationService.save(userRelation);
            if(bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功，我们会尽快与您取得联系"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败请重试"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 微信登录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/wxLogin")
    public JSONObject Login(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String ,Object> map = new HashMap<String, Object>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/wxLogin 接收的参数： "+requestParam);
            System.out.println("wxLogin 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            Integer ag_id = jsonRequest.containsKey("ag_id") ? jsonRequest.getInt("ag_id") : 0;
            Integer promoter_id = jsonRequest.containsKey("promoter_id") ? jsonRequest.getInt("promoter_id") : 0;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";
            String from_type = jsonRequest.containsKey("from_type") ? jsonRequest.getStr("from_type") : null;

            double longitude = jsonRequest.containsKey("lng") && StrUtil.isNotEmpty(jsonRequest.getStr("lng")) ? jsonRequest.getDouble("lng"): 0;
            double latitude = jsonRequest.containsKey("lat") && StrUtil.isNotEmpty(jsonRequest.getStr("lat")) ? jsonRequest.getDouble("lat"): 0;

            String openid = "", unionid = "", sessionkey = "";

            String url = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String,Object> mapParam = new HashMap<>();
            mapParam.put("js_code", code);
            mapParam.put("grant_type", "authorization_code");

            if(platform.equals("wxmini")){
                mapParam.put("appid",appid);
                mapParam.put("secret", secret);
            }else if(platform.equals("wxwork")){
                mapParam.put("appid",appidWork);
                mapParam.put("secret", secretWork);
            }

            String returnParam = HttpUtil.httpClientPost(url, mapParam, "utf-8");
            Gson gson = new Gson();
            Map<String, String> maps = gson.fromJson(returnParam, new TypeToken<Map<String, String>>() {}.getType());
            if(maps != null) {
                openid = maps.containsKey("openid") ? maps.get("openid") : "";
                unionid = maps.containsKey("unionid") ? maps.get("unionid") : "";
                sessionkey =  maps.containsKey("session_key") ? maps.get("session_key") : "";
            } else {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常"),true,true);
            }

            if(!openid.equals("") && !sessionkey.equals("")) {
                String token = UuidUtil.get32UUID();
                QueryWrapper<User> qwUser = new QueryWrapper<>();
                qwUser.eq("open_id",openid);
                qwUser.eq("platform",platform);
                qwUser.last("limit 1");
                User user = userService.getOne(qwUser);
                if(user != null) {//老用户
                    //更新sessionkey
                    user.setSessionKey(sessionkey);
                    if(StrUtil.isEmpty(user.getUnionId())){
                        user.setUnionId(unionid);
                    }
                    user.setLastLoginIp(request.getRemoteAddr());
                    user.setLastActiveTime(new Date());
                    user.setToken(token);
                    user.setLng(new BigDecimal(longitude));
                    user.setLat(new BigDecimal(latitude));
                    user.setPlatform(platform);
                    if(user.getIsAdmin() == null) {
                        user.setIsAdmin(0);
                    }
                    userService.updateLogin(user);
                } else {//新用户
                    user = userService.register(openid,unionid,sessionkey,token,ag_id,platform,promoter_id,longitude,latitude,from_type);
                }

                Parameter parameter = parameterService.getParameterById(1);

                long merCount0 = merService.selectMyMerCount(user.getId(),0);
                map.put("is_mer",merCount0 > 0 ? 1:0);

                map.put("user_id",user.getId());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
                map.put("is_super_admin",0);
                map.put("estate_id",user.getEstateId() != null ?user.getEstateId()  : 0);
                map.put("integral",user.getIntegral());
                map.put("access_token",user.getToken());

                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"登录成功",map),true,false);
            } else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"登录失败"),true,true);
            }

        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 绑定手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getWxPhoneNum")
    public JSONObject getWxPhoneNum(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getWxPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "";
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            //默认  精彩e家
            int type = 1;
            if(platform.equals("wxwork")){
                type = 2;
            }

            String accessToken = wxTemplateService.getAccessToken(type);
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            Map<String,Object> mapParam = new HashMap<>();
            mapParam.put("code", code);
            String returnParam = OkHttpClientUtil.getInstance().postJson(url, JSONUtil.toJsonStr(mapParam));
            System.out.println("返回信息：" + returnParam);
            JSONObject userJson = JSONUtil.parseObj(returnParam);
            if(userJson != null) {
                if(userJson.getInt("errcode") == 0){
                    String phone = userJson.getJSONObject("phone_info").getStr("purePhoneNumber");
                    int ret = userService.bandPhone(phone,user);
                    if(ret > 0){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功",phone),true,false);
                    }else if( ret == -1){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂未开通权限，请找客服开通"),true,true);
                    } else{
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定成功，请重试"),true,true);
                    }
                    //解密成功
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定成功，请重试"),true,true);
                }
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 绑定手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getDyPhoneNum")
    public JSONObject getDyPhoneNum(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getDyPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            String iv = jsonRequest.containsKey("iv") ? jsonRequest.getStr("iv") : "";
            String encryptedData = jsonRequest.containsKey("encryptedData") ? jsonRequest.getStr("encryptedData") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            String url = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String,Object> mapParam = new HashMap<>();
            mapParam.put("appid",appid);
            mapParam.put("secret", secret);
            mapParam.put("js_code", code);
            mapParam.put("grant_type", "authorization_code");
            String returnParam = HttpUtil.httpClientPost(url, mapParam, "utf-8");
            logger.info("登录信息：" + returnParam);
            Gson gson = new Gson();
            Map<String, String> maps = gson.fromJson(returnParam, new TypeToken<Map<String, String>>() {}.getType());
            if(maps != null) {
                String sessionKey = maps.containsKey("session_key") ? maps.get("session_key") : "";
                String resultWx = AESUtil.decryptWXAppletInfo(encryptedData, sessionKey, iv);
                if (StrUtil.isNotEmpty(resultWx)) {
                    System.out.println("手机号解密： "+ resultWx);
                    //{"phoneNumber":"18806331803","purePhoneNumber":"18806331803","countryCode":"86","watermark":{"timestamp":1624344223,"appid":"wxba35b95c0d48f5ca"}}
                    JSONObject userJson = JSONUtil.parseObj(resultWx);
                    String phone = userJson.getStr("phoneNumber");

                    int ret = userService.bandPhone(phone,user);
                    if(ret > 0){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功",phone),true,false);
                    }else if( ret == -1){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂未开通权限，请找客服开通"),true,true);
                    } else{
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定成功，请重试"),true,true);
                    }
                    //解密成功
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定成功，请重试"),true,true);
                }
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取用户信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfoById")
    public JSONObject getUserInfoById(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            logger.info("user/getUserInfoById:  "+ requestParam);
            System.out.println("user/getUserInfoById 接受参数：" + requestParam + "      " +  DateUtil.getTime());

            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;


            User user = userService.findById(user_id);
            if(user != null){
//                MerUser merUser = merUserService.getMerUser(user.getId());
                user.setLastActiveTime(new Date());
                user.setLastLoginIp(request.getRemoteAddr());
                if(StrUtil.isEmpty(user.getToken())){
                    user.setToken(UuidUtil.get32UUID());
                }
                userService.updateLogin(user);

                Map<String ,Object> map = new HashMap<>();
                map.put("is_reLogin",0);

                long merCount0 = merService.selectMyMerCount(user_id,0);
                map.put("is_mer",merCount0 > 0 ? 1:0);


                map.put("user_no",user.getUserNo());
                map.put("user_id",user.getId());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
                map.put("phone_num",user.getPhoneNum());
                map.put("integral",user.getIntegral());
                map.put("access_token",user.getToken());
                map.put("estate_id", user.getEstateId() != null ? user.getEstateId()  : 0);
                map.put("open_id",user.getOpenId());
                map.put("is_new_user",user.getIsNewUser());


                map.put("estate_state", 0);
                if(user.getEstateId() != null){
                    Estate estate = estateService.findById(user.getEstateId());
                    if(estate != null){
                        map.put("estate_name",estate.getEstateName());
                        map.put("estate_telphone", estate.getTelphone());
                        map.put("estate_state", estate.getState());
                    }
                }

                map.put("band_estate_count",0);
                QueryWrapper<EstateRoomBangUser> qwRoom = new QueryWrapper<>();
                qwRoom.eq("bang_wx_user_id", user_id);
                long estateCount = estateRoomBangUserService.count(qwRoom);
                map.put("band_estate_count",estateCount);


                if(StrUtil.isNotEmpty(user.getFaceUrl())){
                    if(!user.getFaceUrl().contains("https")){
                        map.put("face_url", imgPrefix + user.getFaceUrl());
                    }else{
                        map.put("face_url",  user.getFaceUrl());
                    }
                }
                map.put("nick_name", "");
                if(StrUtil.isNotEmpty(user.getNickName())){
                    map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
                }
                map.put("user_no", user.getUserNo());

                Parameter parameter = parameterService.getParameterById(1);
                map.put("is_show_wx_ad",parameter.getIsShowWxAd());
                map.put("is_focus_mp",0);
                map.put("is_need_sms_band_room", parameter.getIsNeedSmsBandRoom());

                QueryWrapper<UserMp> qw = new QueryWrapper<>();
                qw.eq("union_id",user.getUnionId());
                UserMp userMp = userMpService.getOne(qw);
                if(userMp != null){
                    map.put("is_focus_mp",1);
                }


                map.put("is_attendance",0);
                Integer[] roleIds = { 3, 4};
                QueryWrapper<SysUser> qwSysUser = new QueryWrapper<>();
                qw.select("user_id");
                qwSysUser.eq("user_id",user.getSysUserId());
                qwSysUser.eq("status", "0");
                qwSysUser.in("role_id", Arrays.asList(roleIds));
                long sysUserCount = sysUserService.count(qwSysUser);
                if(sysUserCount > 0){
                    map.put("is_attendance",1);
                }

                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
            }else{
                Map<String ,Object> map = new HashMap<>();
                map.put("is_reLogin",0);
//                if(user_id == 1){
//                    map.put("is_reLogin",1);
//                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在",map),true,false);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取用户信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfoByOpenId")
    public JSONObject getUserInfoByOpenId(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            logger.info("user/getUserInfoByOpenId:  "+ requestParam);
            System.out.println("user/getUserInfoByOpenId 接受参数：" + requestParam + "      " +  DateUtil.getTime());

            String open_id = jsonRequest.containsKey("open_id") ? jsonRequest.getStr("open_id") : null;
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("open_id",open_id);
            qw.last("limit 1");
            User user = userService.getOne(qw);
            if(user != null){
//                MerUser merUser = merUserService.getMerUser(user.getId());
                user.setLastActiveTime(new Date());
                user.setLastLoginIp(request.getRemoteAddr());
                if(StrUtil.isEmpty(user.getToken())){
                    user.setToken(UuidUtil.get32UUID());
                }
                userService.updateById(user);
                Map<String ,Object> map = new HashMap<String, Object>();
                map.put("user_id",user.getId());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);

                long merCount0 = merService.selectMyMerCount(user.getId(),0);
                map.put("is_mer",merCount0 > 0 ? 1:0);

                map.put("phone_num",user.getPhoneNum());
                map.put("integral",user.getIntegral());
                map.put("access_token",user.getToken());

                Parameter parameter = parameterService.getParameterById(1);
                map.put("is_show_wx_ad",parameter.getIsShowWxAd());
                map.put("estate_id",user.getEstateId() != null ?user.getEstateId()  : 0);
                map.put("is_focus_mp",0);

                QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
                qwMp.eq("union_id",user.getUnionId());
                UserMp userMp = userMpService.getOne(qwMp);
                if(userMp!=null){
                    map.put("is_focus_mp",1);
                }

                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取用户信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfo")
    public JSONObject getUserInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
//            String encryptedData = jsonRequest.containsKey("encryptedData") ? jsonRequest.getStr("encryptedData") : "";
//            String iv = jsonRequest.containsKey("iv") ? jsonRequest.getStr("iv") : "";
//            String rawData = jsonRequest.containsKey("rawData") ? jsonRequest.getStr("rawData") : "";

            System.out.println("user/getUserInfo 接受参数：" + requestParam + "      " +  DateUtil.getTime());
            logger.info("user/getUserInfo:  "+ requestParam);

//            System.out.println("encryptedData: " + encryptedData);
//            System.out.println("iv: " + iv);
//            System.out.println("rawData: " + rawData);

//            String userInfo = "";
            String unionId = "",nickname = "";
//            int gender = 1;
            User user = userService.findById(user_id);
            if(user != null){
//                userInfo = AESUtil.decryptWXAppletInfo(encryptedData,user.getSessionKey(),iv);
//                JSONObject decodeJSON = null;
//                if(userInfo!=null && !userInfo.equals("")){
//                    decodeJSON = JSONUtil.parseObj(userInfo);
//                    if(JSONUtil.isNull(decodeJSON)){
//                        unionId = decodeJSON.containsKey("unionId") ? decodeJSON.getStr("unionId") :"";
//                    }
//                }
                System.out.println("unionId: " + unionId);
//                String ssss = "";
//                JSONObject userInfoJson = null;
//                if(!rawData.equals("")){
//                    userInfoJson = JSONUtil.parseObj(rawData);
//                    if(userInfoJson != null && userInfoJson.size() > 0){
//                        if(nickname.equals("")){
//                            System.out.println("nickname 处理前: " + nickname);
//                            nickname = userInfoJson.containsKey("nickName") ? userInfoJson.getStr("nickName") : user.getNickName();
//                            nickname = EmojiParser.parseToAliases(nickname);
//                            System.out.println("nickname 处理后: " + nickname);
//                        }
//                        gender = userInfoJson.containsKey("gender") ? userInfoJson.getInt("gender"):1;
//                    }
//                }

//                user.setSex(gender);
//                if(!unionId.equals("")){
//                    user.setUnionId(unionId);
//                }

                if(StrUtil.isNotEmpty(user.getUnionId())){
                    UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
                    if(userMp!=null){
                        if(userMp.getMerId()!=null &&
                                (user.getMerId() == null || user.getMerId() == 0)){
                            user.setMerId(userMp.getMerId());
                            user.setUserType(1);
                            user.setIsAdmin(1);
                        }
                    }
                }
                userService.updateLogin(user);

                MerUser merUser = merUserService.getMerUser(user.getId());
                Map<String ,Object> map = new HashMap<>();
                map.put("user_id",user.getId());
                map.put("user_no",user.getUserNo());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
                map.put("is_mer", merUser != null ? 1 : 0);
                map.put("estate_id",user.getEstateId() != null ?user.getEstateId()  : 0);
                map.put("is_focus_mp",0);
                map.put("is_new_user",user.getIsNewUser());

                QueryWrapper<UserMp> qw = new QueryWrapper<>();
                qw.eq("union_id",user.getUnionId());
                UserMp userMp = userMpService.getOne(qw);
                if(userMp!=null){
                    map.put("is_focus_mp",1);
                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"用户不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取用户个人中心的显示数据  包括 优惠券的数量 底部广告，订单类型的数量
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfoData")
    public JSONObject getUserInfoData(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{

            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "";
            //1.获取订单类型的数量  待付款、待发货、已发货、待评价、售后
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            List<OrderItemArr> list = new ArrayList<>();
            //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
            // 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货 10  - 已完成
            String[] status = {"全部","待支付", "待核销", "待评价", "已评价"};
            int[] states = {-1, 0, 2, 3, 4};//3
            for(int i = 0; i < status.length; i++){
                OrderItemArr orderItemArr0 = new OrderItemArr();
                orderItemArr0.setId(states[i]);
                int orderNum = productOrderService.getOrderCountByState(user_id,states[i]);
                orderItemArr0.setOrderNum(orderNum);
                orderItemArr0.setUrl("/pages/order/productList/index?from_type=0&state=" + states[i] + "&index="+(i));
                orderItemArr0.setOrderStatus(status[i]);
                orderItemArr0.setImgSrc(imgUrlOss + "simple/image/orderlist" + i +".png");
                list.add(orderItemArr0);
            }
            map.put("orderItemArr",list);

            //3.底部广告
            AdBanner banner = adBannerService.getBannerByAdType(2);
            map.put("banner",banner);
            if(banner != null){
                map.put("hasBanner",1);
            }else{
                map.put("hasBanner",0);
            }

            Integer[] s = {0,1};
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
            qw.select("id");
            qw.eq("user_id",user_id);
            qw.in("status",Arrays.asList(s));
            long productNoPayCount = productOrderService.count(qw);
            map.put("product_no_pay", productNoPayCount);

            QueryWrapper<PropertyFeeOrder> qw1 = new QueryWrapper<>();
            qw1.select("id");
            qw1.eq("user_id",user_id);
            qw1.in("state",Arrays.asList(s));
            long propertyNoPayCount = propertyFeeOrderService.count(qw1);
            map.put("property_no_pay", propertyNoPayCount);

            map.put("user_no",user.getUserNo());

            map.put("phone_num",user.getPhoneNum());
            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgPrefix + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }
            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }


            long merCount0 = merService.selectMyMerCount(user_id,0);
            map.put("is_mer", merCount0 > 0 ? 1 : 0);

            map.put("is_test_user",user.getIsTestUser());


            Parameter parameter = parameterService.getParameterById(1);
            map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
            map.put("phone_num",user.getPhoneNum());

            map.put("estate_id",user.getEstateId() != null ?user.getEstateId()  : 0);
            map.put("is_show_mer",parameter.getIsShowMer());

            QueryWrapper<RepairRecord> qwRepair = new QueryWrapper<>();
            qwRepair.select("id");
            qwRepair.eq("user_id",user_id);
            long repairCount = repairRecordService.count(qwRepair);
            map.put("repair_count",repairCount);

            //1.标题TAB菜单
            //彩恒云 和 精彩e家的 分开显示
            if(platform.equals("wxwork")){
                List<TitleMenu> menuList = titleMenuService.selectBySpecial("chypersonal", null);
                map.put("menuList",menuList);

                int approveCountCheck = approveRegRecordService.getAdminHandleCount(user, 0);
                map.put("approveCountCheck",approveCountCheck);

            }else{
                List<TitleMenu> menuListNew = new ArrayList<>();
                List<TitleMenu> menuList = titleMenuService.selectBySpecial("personal", null);
                if(CollUtil.isNotEmpty(menuList)){
                    for (TitleMenu menu : menuList){
                        if(StrUtil.isEmpty(menu.getPurviewType())){
                            menuListNew.add(menu);
                        }else if(StrUtil.isNotEmpty(menu.getPurviewType())){
                            if(menu.getPurviewType().equals("mer")){
                                if(merCount0 > 0){
                                    menuListNew.add(menu);
                                }
                            }
                        }else{
                            menuListNew.add(menu);
                        }
                    }
                }
                map.put("menuList",menuListNew);
            }

            //客服人员角色
            long estateUser = estateUserService.getUserCountByUserType(user_id,1);
            map.put("estate_user_count",estateUser);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 修改支付密码
     *
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/updatePayPwd")
    public JSONObject updatePayPwd(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try {
            if (requestParam.equals("")) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "参数异常"), true, true);
            }
            logBefore(logger, "user/updatePayPwd 接收的参数： " + requestParam);
            System.out.println("user/updatePayPwd 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String pwd = jsonRequest.containsKey("pwd") ? jsonRequest.getStr("pwd").trim() : "";
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num").trim() : "";
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";

            User user = userService.findById(user_id);
            if (user == null) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "当前用户不存在"), true, true);
            }

            if(StrUtil.isEmpty(code)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "验证码不能为空"), true, true);
            }


            if (code.length() != 6) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "验证码输入错误"), true, true);
                return result;
            }

            redisTemplate.opsForValue().set(phone_num, code, 300L, TimeUnit.SECONDS);
            //取出所有有关该手机号的短信验证码
            String phoneCode = redisTemplate.opsForValue().get(phone_num).toString();
            if (phoneCode == null || phoneCode.equals("")) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "短信验证失败"), true, true);
            } else {
                redisTemplate.delete(phone_num);
            }

            user.setPayPwd(pwd);
            boolean bl = userService.updateById(user);
            if (bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "设置成功"), true, true);
            } else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "设置失败"), true, true);
            }
        } catch (Exception e) {
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR, "系统异常", e.getMessage()), true, true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 修改当前所在城市
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/updateLocation")
    public JSONObject updateLocation(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try {
            if (requestParam.equals("")) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "参数异常"), true, true);
            }
            logBefore(logger, "user/updateLocation 接收的参数： " + requestParam);
            System.out.println("user/updateLocation 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            double longitude = jsonRequest.containsKey("longitude") && StrUtil.isNotEmpty(jsonRequest.getStr("longitude")) ? jsonRequest.getDouble("longitude"): 0;
            double latitude = jsonRequest.containsKey("latitude") && StrUtil.isNotEmpty(jsonRequest.getStr("latitude")) ? jsonRequest.getDouble("latitude"): 0;


            User user = userService.findById(user_id);
            if (user == null) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "当前用户不存在"), true, true);
            }

            if(latitude == 0 || longitude == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "未获取当前定位，请去设置中心打开"), true, true);
            }

            JSONObject locationInfo = BaiduMapUtils.getLocationInfo(latitude+"", longitude+"");
            int status = locationInfo.getInt("status");
            if(status == 0){
                String province = locationInfo.getJSONObject("result").getJSONObject("addressComponent").getStr("province");
                String city = locationInfo.getJSONObject("result").getJSONObject("addressComponent").getStr("city");
                String district = locationInfo.getJSONObject("result").getJSONObject("addressComponent").getStr("district");
                user.setProvince(province);
                user.setCity(city);
                user.setDistrict(district);
                boolean bl = userService.updateById(user);
                if (bl) {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "设置成功"), true, true);
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "设置失败"), true, true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "获取定位信息失败"), true, true);
            }
        } catch (Exception e) {
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR, "系统异常", e.getMessage()), true, true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 意见反馈
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addFeedback")
    public JSONObject addFeedback(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") :"";

            FeedBack feedBack = new FeedBack();
            feedBack.setUserId(user_id);
            feedBack.setPhoneNum(phone_num);
            feedBack.setContent(content);
            feedBack.setCreateTime(new Date());
            boolean ret = feedBackService.save(feedBack);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"反馈提交成功，客服会在24小时内跟您取得联系"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"意见反馈失败，请稍后重试"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送验证码
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/sendCode")
    public JSONObject sendValidateCode(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String phoneNum = jsonRequest.containsKey("phoneNum") ? jsonRequest.getStr("phoneNum") : null;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : null;

            if (!phoneNum.equals("") && phoneNum.length() == 11) {
                SmsTemplate sms = smsTemplateService.selectByUniqueColumn("sms_type",1);
                if(sms == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "发送失败"), true, true);
                }

                Integer smsType = 1;
                if(platform.equals("wxmini")){
                    smsType = 1;
                }else if(platform.equals("wxwork")){
                    smsType = 2;
                }

                //验证码
                int code = Tools.getRandomNum();//生成6位随机数
                String responseCode = smsTemplateService.sendSmsByPhoneCode(code + "",phoneNum, smsType);
                if(responseCode.equals("OK")) {
                    redisTemplate.opsForValue().set(phoneNum, code, 900L, TimeUnit.SECONDS);
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"发送成功"),true,false);
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"验证码发送失败，请重试"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请输入正确的手机号"),true,true);
            }
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(""+e.getMessage());
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"系统异常"),true,true);
        }
        return result;
    }

    /**
     * 绑定手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/bandPhone")
    public JSONObject bandPhone(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/bandPhone 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num").trim() : "";
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(code != null){
                if (code.length() != 6) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"验证码必须为6位"),true,true);
                }

                redisTemplate.opsForValue().set(phone_num, code, 300L, TimeUnit.SECONDS);
                //取出所有有关该手机号的短信验证码
                String phoneCode = redisTemplate.opsForValue().get(phone_num).toString();
                if (phoneCode == null || phoneCode.equals("")) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"短信验证失败"),true,true);
                }else{
                    redisTemplate.delete(phone_num);
                }
            }

            user.setPhoneNum(phone_num);
            boolean bl = userService.updateById(user);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "绑定成功"), true , true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true , true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 绑定考勤账号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/bandDutyUser")
    public JSONObject bandDutyUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/bandDutyUser 绑定考勤账号 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num").trim() : "";
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(code != null){
                if (code.length() != 6) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"验证码必须为6位"),true,true);
                }

                redisTemplate.opsForValue().set(phone_num, code, 300L, TimeUnit.SECONDS);
                //取出所有有关该手机号的短信验证码
                String phoneCode = redisTemplate.opsForValue().get(phone_num).toString();
                if (phoneCode == null || phoneCode.equals("")) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"短信验证失败"),true,true);
                }else{
                    redisTemplate.delete(phone_num);
                }
            }

            user.setPhoneNum(phone_num);
            boolean bl = userService.updateById(user);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "绑定成功"), true , true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true , true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 绑定手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getPhoneNum")
    public JSONObject getPhoneNum(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            String iv = jsonRequest.containsKey("iv") ? jsonRequest.getStr("iv") : "";
            String encryptedData = jsonRequest.containsKey("encryptedData") ? jsonRequest.getStr("encryptedData") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            String url = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String,Object> mapParam = new HashMap<String,Object>();
            mapParam.put("appid",appid);
            mapParam.put("secret", secret);
            mapParam.put("js_code", code);
            mapParam.put("grant_type", "authorization_code");
            String returnParam = HttpUtil.httpClientPost(url, mapParam, "utf-8");
            logger.info("登录信息：" + returnParam);
            Gson gson = new Gson();
            Map<String, String> maps = gson.fromJson(returnParam, new TypeToken<Map<String, String>>() {}.getType());
            if(maps != null) {
                String sessionKey = maps.containsKey("session_key") ? maps.get("session_key") : "";
                String resultWx = AESUtil.decryptWXAppletInfo(encryptedData, sessionKey, iv);
                if (StrUtil.isNotEmpty(resultWx)) {
                    System.out.println("手机号解密： "+ resultWx);
                    JSONObject userJson = JSONUtil.parseObj(resultWx);
                    String phone = userJson.getStr("phoneNumber");
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功",phone),true,false);
                    //解密成功
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请重试"),true,true);
                }
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/searchUser")
    public JSONObject searchUser(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getInt("sys_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(sys_user_id);
            if(sysUser  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该绑定账号不存在"),true,true);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功"),false,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  判断是否关注公众号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserFocusMp")
    public JSONObject getUserFocusMp(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getUserFocusMp  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            UserMp userMp = userMpService.getLastUserMp();
            userService.reloadUserMp(userMp.getOpenId());

            //is_focus_mp
            int isFocus = 0;
            QueryWrapper<UserMp> qw = new QueryWrapper<>();
            qw.eq("union_id",user.getUnionId());
            qw.last("limit 1");
            UserMp userMp1 = userMpService.getOne(qw);
            if(userMp1!=null){
                isFocus = 1;
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",isFocus),true,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getAccountInfo")
    public JSONObject getAccountInfo(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Estate estate = estateService.findById(user.getEstateId());
            if(estate!=null){
                user.setEstateName(estate.getEstateName());
                map.put("estate_name",estate.getEstateName());
                map.put("estate_telphone",estate.getTelphone());
            }

            map.put("user",user);
            map.put("phone_num",user.getPhoneNum());
            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgPrefix + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }
            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }
            map.put("is_has_pay_pwd", 0);
            if(StrUtil.isNotEmpty(user.getPayPwd())){
                map.put("is_has_pay_pwd",1);
            }

            List<String> estate_names = new ArrayList<>();
            List<EstateRoom> estateRooms = estateRoomService.getRoomListByUserId(user_id,"");
            if(estateRooms != null){
                for (EstateRoom room : estateRooms){
                    estate_names.add(room.getEstateName() + " " + room.getRoomNo());
                    String realName = room.getRealName();
                    if(StrUtil.isNotEmpty(realName)){
                        realName = realName.substring(0,1) + "**";
                        room.setRealName(realName);
                    }

                    String phone_num = room.getPhoneNum();
                    if(StrUtil.isNotEmpty(phone_num) && phone_num.length() >= 11){
                        phone_num = phone_num.substring(0,3) + "****" + phone_num.substring(phone_num.length() - 4,phone_num.length());
                        room.setPhoneNum(phone_num);
                    }
                }
            }
            map.put("estate_names", estate_names);
            map.put("rooms", estateRooms);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",map),false,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getAccountInfoByManager")
    public JSONObject getAccountInfoByManager(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

//            SysUser sysUser  = sysUserService.findById(user.getSysUserId());
            Estate estate = null;//estateService.findById(user.getEstateId());
            EstateUser estateUser = estateUserService.getEstateBySysUser(user.getSysUserId());
            if(estateUser != null){
                estate = estateService.findById(estateUser.getEstateId());
                if(estate!=null){
                    user.setEstateName(estate.getEstateName());
                    map.put("estate_name",estate.getEstateName());
                    map.put("estate_telphone",estate.getTelphone());
                }
            }

            map.put("user",user);
            map.put("phone_num",user.getPhoneNum());
            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgPrefix + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }
            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }

            List<String> estate_names = new ArrayList<>();
            List<Estate> estateList = new ArrayList<>();
            List<EstateUser> estateUsers = estateUserService.getEstateListByUserId(user_id);
            if(estateUsers != null){
                for (EstateUser estateUser1 : estateUsers){
                    Estate estate1 = estateService.findById(estateUser1.getEstateId());
                    if(estate1!=null){
                        estate_names.add(estate1.getEstateName());
                    }
                    estateList.add(estate1);
                }
            }
            map.put("estate_names", estate_names);
            map.put("estateList", estateList);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",map),false,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/updateEstateId")
    public JSONObject updateEstateId(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            if(estate_id == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择所属小区"),true,true);
            }

            Map<String, Object> map = new HashMap<>();
            Estate estate = estateService.findById(estate_id);
            if(estate!=null){
                user.setEstateId(estate_id);
                user.setPropertyId(estate.getPropertyId());
                map.put("estate_id", estate_id);
                map.put("estate_name", estate.getEstateName());
                map.put("estate_telphone", estate.getTelphone());
            }


            boolean bl = userService.updateById(user);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"保存成功",map ),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"保存失败"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/updateNickName")
    public JSONObject updateNickName(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/updateNickName  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String nickName = jsonRequest.containsKey("nickName") ? jsonRequest.getStr("nickName") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }
            user.setNickName(nickName);

            boolean bl = userService.updateById(user);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"保存成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"保存失败"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/updateFaceUrlOld")
    public JSONObject updateFaceUrl(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/updateFaceUrl  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String faceUrl = jsonRequest.containsKey("face_url") ? jsonRequest.getStr("face_url") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            user.setFaceUrl(faceUrl);
            boolean bl = userService.updateById(user);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"保存成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"保存失败"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家入驻的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/updateFaceUrl")
    public JSONObject uploadImgRepair(@RequestParam("user_id") int user_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            User user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "用户不存在"), true, true);
            }

            String faceUrl = "";
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certUrl = maps.get(key);
                        if (!certUrl.isEmpty()) {
                            String prefix = certUrl.getOriginalFilename().substring(certUrl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "user_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certUrl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_USER_FACE;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        OssUtil.uploadObs(certUrl.getInputStream(),fileName,upload_type);

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certUrl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);
                                        faceUrl = imgPrefix + img_key;
                                        user.setFaceUrl(img_key);
                                        userService.updateById(user);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    return Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "上传成功",faceUrl), true, false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     *  城市列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/city/listByCharacters")
    public JSONObject listByCharacters(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/city/listByCharacters 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;


            List<Map<String,Object>> cityList = cityService.getCityListByPinyinGroup(keyword);
            Map<String,Object> map = new HashMap<>();
            map.put("cityList",cityList);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",cityList.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

}
